﻿using Microsoft.EntityFrameworkCore;
using XLZF.MicroServices.ModelMigration;
using XLZF.MicroServices.Models;

namespace XLZF.MicroServices.AuthenticationCenter.IdentityUserStore;

public class UserStore
{
    private readonly UserStoreDbContext _dbContext;

    public UserStore(UserStoreDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    /// <summary>
    /// 根据SubjectID查询用户信息
    /// </summary>
    /// <param name="subjectId">用户id</param>
    /// <returns></returns>
    public IdentityUser FindBySubjectId(string subjectId)
    {
        return _dbContext.Set<IdentityUser>().Where(r => r.SubjectId.Equals(subjectId)).Include(r => r.IdentityUserClaims).SingleOrDefault();
    }

    /// <summary>
    /// 根据用户名查询用户
    /// </summary>
    /// <param name="username">用户</param>
    /// <returns></returns>
    public IdentityUser FindByUsername(string username)
    {
        return _dbContext.Set<IdentityUser>().Where(r => r.Username.Equals(username)).Include(r => r.IdentityUserClaims).SingleOrDefault();
    }

    /// <summary>
    /// 验证登录密码
    /// </summary>
    /// <param name="username"></param>
    /// <param name="password"></param>
    /// <returns></returns>
    public bool ValidateCredentials(string username, string password)
    {
        //password = Config.MD5Str(password);
        var user = _dbContext.Set<IdentityUser>().Where(r => r.Username.Equals(username)
        && r.Password.Equals(password)).Include(r => r.IdentityUserClaims).SingleOrDefault();
        return user != null;
    }
}